import datetime

from flask import Blueprint, render_template, request, redirect
from .models import *

# 蓝图，传入蓝图名称和当前模块
blue = Blueprint('user',__name__)

@blue.route('/')
@blue.route('/home/')
def home():
    # 4、获取cookie中保存的username
    username = request.cookies.get('user_cookie')
    print("获取cookies中的user：",username)
    # 渲染：home.html
    return render_template('home.html',username=username) #向模板语言中的username传参，显示到前端页面

@blue.route('/login/', methods=['GET', 'POST'])
def login():
    # 如果请求方法是GET
    if request.method == 'GET':
        # 模板渲染：login.html
        return render_template('login.html')
    # 如果请求方法是POST
    elif request.method == 'POST':
        print("执行post请求！")
        # 获取客户端请求的username和password
        username = request.form['username']
        print("获取username：",username)
        password = request.form['password']
        print("获取password：", password)
        # 2、模拟登录
        # 如果username和password满足if表达式
        if username == 'admin' and password == '123456':
            print("登录成功 用户名密码正确")
            # 重定向(路由)：/home
            response = redirect('/home/')
            # 3、设置cookies
            # response.set_cookie('user_cookie', username)  #默认浏览器关闭则cookie失效
            response.set_cookie('user_cookie', username , max_age=3600*24)  #设置过期时间
            # response.set_cookie('user_cookie', username, expires=datetime.datetime(2025,1,3))  #指定过期日期
            return response
        else:
            return "用户名或密码错误"

# 注销
@blue.route('/logout/',methods=['GET','POST'])
def logout():
    # 刷新页面：重定向
    response = redirect('/home/')
    # 删除cookies
    response.delete_cookie('user_cookie')
    return response
